import 'dart:collection';

import 'package:dio/dio.dart';
import 'package:tx_live_plugin_example/util/crypto_utils.dart';
import 'package:tx_live_plugin_example/util/logic_presenter.dart';

///todo 签名key 不可上传到git
const String SIGN_KEY = "";

class ParamInterceptor extends InterceptorsWrapper {

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler)async {
    bool isPost = options.method == "POST";
    if (isPost && options.data is Map) {
      options.data = _addParams(options.data);
    } else {
      options.queryParameters = await _addParams(options.queryParameters);
    }
    super.onRequest(options, handler);
  }

  Future<Map<String, dynamic>> _addParams(Map<String, dynamic>? data) async{
    data ??= {};
    LogicPresenter.getDefaultParams().forEach((key, value) {
      if (!data!.containsKey(key)) {
        data[key] = value;
      }
    });
    data["sign"] = await _signParams(data);
    data["signType"] = "md5";
    return data;
  }


  ///对参数进行签名
  Future<String> _signParams(Map<String, dynamic> map) async{
    //防止map出现不是String的value，在SplayTreeMap中无法转换
    Map<String, String> test = Map();
    map.forEach((key, value) {
      //值非文件
      if (value is! MultipartFile) {
        test[key] = "$value";
      }
    });
    //根据key进行排序
    SplayTreeMap<String, String> treeMap =
    SplayTreeMap.from(test, (key1, key2) => key1.compareTo(key2));
    String before = '';
    treeMap.forEach((key, value) {
      before += "$key=$value&"; //最后一个符号，用于后面的key使用
    });
    String key = SIGN_KEY;
    before += "key=$key";

    String sign = await CryptoUtils.md5String(before);
    return sign;
  }
}
